/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxdiameter = 0;
    int Longestdiameter(TreeNode* root)
    {
        if (root == nullptr) return 0;
        int leftMax = Longestdiameter(root->left);
        int rightMax = Longestdiameter(root->right);
        int preDiameter = leftMax + rightMax;
        maxdiameter = max(maxdiameter, preDiameter);

        return max(leftMax, rightMax) + 1;
    }

    int diameterOfBinaryTree(TreeNode* root)
    {
        Longestdiameter(root);
        return maxdiameter;
    }
};